<template>
  <div class="chat-container">
    <Header :url="userImageUrl" />
    <div class="chat-main">
      <div class="chat-sidebar">
        <div class="sidebar-header">
          <h3>聊天记录</h3>
          <el-button type="primary" size="small" @click="createNewChat" class="new-chat-btn">
            <i class="el-icon-plus"></i> 新建聊天
          </el-button>
        </div>
        <div class="chat-contacts">
          <div 
            v-for="(chat, index) in chats" 
            :key="chat.id" 
            class="contact-item"
            :class="{ 'active': activeContact === chat.id }"
            @click="selectContact(chat.id)"
          >
            <div class="contact-main">
              <el-avatar :src="chat.avatar" size="small"></el-avatar>
              <div class="contact-info">
                <div class="contact-name">{{ chat.title || '新的聊天' }}</div>
              </div>
              <div class="contact-meta">
                <span class="time">{{ chat.time }}</span>
              </div>
            </div>
            <div class="contact-actions">
              <el-tooltip content="修改标题" placement="top" :open-delay="300">
                <i class="el-icon-edit action-icon edit-icon" @click.stop="openRenameDialog(chat.id)"></i>
              </el-tooltip>
              <el-tooltip content="删除聊天" placement="top" :open-delay="300">
                <i class="el-icon-delete action-icon delete-icon" @click.stop="deleteChat(chat.id)"></i>
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>
      <div class="chat-content">
        <div v-if="activeContact !== null" class="chat-header">
          <h3>{{ getActiveChatTitle() }}</h3>
        </div>
        <div v-else class="chat-header">
          <h3>欢迎使用专业翻译解释助手</h3>
        </div>
        
        <div class="messages-container" ref="messagesContainer">
          <div v-if="activeContact !== null && messages.length > 0" class="messages">            <div 
              v-for="(message, index) in messages" 
              :key="index"
              class="message"
              :class="{ 'own-message': message.own }"
            >
              <el-avatar 
                :src="message.own ? userImageUrl : getActiveChatAvatar()" 
                size="small"
              ></el-avatar>              <div class="message-content">
                <!-- RAG信息显示 -->                <div v-if="message.ragInfo && message.ragInfo.basedOnRag" class="rag-info-container">
                  <div class="rag-header">
                    <div class="rag-title">
                      <i class="el-icon-connection"></i>
                      <span class="rag-badge">知识库增强</span>
                      <el-tooltip content="此回答基于知识库检索增强生成" placement="top">
                        <i class="el-icon-question" style="margin-left: 4px; color: #999; cursor: help;"></i>
                      </el-tooltip>
                    </div>
                    <div class="rag-stats">
                      <el-tooltip content="从知识库中检索的相关条目数量" placement="top">
                        <el-tag size="mini" type="info">
                          <i class="el-icon-search"></i> 检索: {{ message.ragInfo.ragCount }}
                        </el-tag>
                      </el-tooltip>
                      <el-tooltip content="符合相似度阈值的有效条目数量" placement="top">
                        <el-tag size="mini" type="success">
                          <i class="el-icon-check"></i> 有效: {{ message.ragInfo.validRagCount }}
                        </el-tag>
                      </el-tooltip>
                      <el-tooltip content="检索结果的平均相似度，越高表示匹配度越好" placement="top">
                        <el-tag size="mini" :type="getSimilarityTagType(message.ragInfo.averageSimilarity)">
                          <i class="el-icon-data-line"></i> 平均: {{ (message.ragInfo.averageSimilarity * 100).toFixed(1) }}%
                        </el-tag>
                      </el-tooltip>
                      <el-tooltip content="最高相似度，表示最佳匹配的相关性" placement="top">
                        <el-tag size="mini" :type="getSimilarityTagType(message.ragInfo.maxSimilarity)">
                          <i class="el-icon-top"></i> 最高: {{ (message.ragInfo.maxSimilarity * 100).toFixed(1) }}%
                        </el-tag>
                      </el-tooltip>
                    </div>
                  </div>
                  
                  <!-- 可信度指示器 -->
                  <div class="rag-confidence">
                    <span class="confidence-label">回答可信度：</span>
                    <el-progress 
                      :percentage="getConfidencePercentage(message.ragInfo)" 
                      :color="getConfidenceColor(message.ragInfo)"
                      :stroke-width="6"
                      :show-text="true"
                      :format="() => getConfidenceText(message.ragInfo)">
                    </el-progress>
                  </div>
                  
                  <!-- RAG结果详情 -->
                  <div v-if="message.ragInfo.ragResults && message.ragInfo.ragResults.length > 0" class="rag-results">
                    <el-collapse accordion>
                      <el-collapse-item title="查看参考内容" name="rag-details">
                        <div v-for="(result, idx) in message.ragInfo.ragResults" :key="idx" class="rag-result-item">
                          <div class="rag-result-header">
                            <span class="similarity-score">相似度: {{ Math.round(result.similarity * 100) }}%</span>
                            <el-progress 
                              :percentage="Math.round(result.similarity * 100)" 
                              :color="getSimilarityColor(result.similarity)"
                              :stroke-width="4"
                              :show-text="false">
                            </el-progress>
                          </div>
                          <div class="rag-result-content">
                            <div class="rag-question">
                              <strong>问题:</strong> {{ result.questionSummary }}
                            </div>
                            <div class="rag-answer">
                              <strong>参考内容:</strong> {{ result.answerSummary }}
                            </div>
                          </div>
                        </div>
                      </el-collapse-item>
                    </el-collapse>
                  </div>
                </div>
                
                <div class="message-text" v-html="formatMessageText(message.text)"></div>
                <div class="message-time">{{ message.time }}</div>
              </div>
            </div>
          </div>
          <div v-else class="no-chat-selected">
            <img src="https://cdn.iconscout.com/icon/free/png-256/free-chat-2639493-2187526.png" alt="Chat Icon" class="chat-icon"/>
            <p>输入文本获取专业翻译和解释</p>
            <el-button type="primary" @click="createNewChat" class="new-chat-big-btn">
              <i class="el-icon-plus"></i> 创建新聊天
            </el-button>
          </div>
        </div>
        
        <div v-if="activeContact !== null" class="chat-input">
          <div class="input-actions">
            <i class="el-icon-mic" title="语音输入"></i>
            <i class="el-icon-refresh" title="清空输入"></i>
          </div>
          <div class="input-field">
            <textarea 
              v-model="newMessage" 
              placeholder="输入您的英语问题..." 
              @keyup.enter.ctrl="sendMessage"
            ></textarea>
            <small class="input-tip">按Ctrl+Enter发送</small>
          </div>
          <el-button type="primary" @click="sendMessage" :disabled="!newMessage.trim()">
            发送
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 修改标题对话框 -->
    <el-dialog
      title="修改聊天标题"
      v-model:modelValue="dialogVisible"
      :width="'400px'"
      :modal="true"
      :append-to-body="true"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      custom-class="rename-dialog"
      center ="true"
    >
      <el-input v-model="newTitle" placeholder="请输入新标题" ref="titleInput"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRename">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Header from "@/components/Header.vue";
import request from "@/utils/request.js"; 
import '@/css/rag-styles.css'; // 导入RAG样式

export default {
  name: "Chat",
  components: {
    Header
  },
  data() {
    return {
      chats: [],
      activeContact: null,
      messages: [],
      newMessage: "",
      userImageUrl: this.$store.getters.userImageUrl,
      botAvatar: "https://img.icons8.com/color/48/000000/translator.png",
      dialogVisible: false,
      newTitle: "",
      currentEditingChatId: null,
      loading: false, // 添加loading状态
    };
  },
  created() {
    // 验证用户登录状态
    this.validateUser();
    // 从后端获取聊天记录
    this.fetchChats();
  },
  methods: {
    // 验证用户登录状态
    validateUser() {
      const userJson = localStorage.getItem("user");
      if (!userJson) {
        this.$message.error('用户信息不存在，请重新登录');
        this.$router.push('/login');
        return false;
      }
        try {
        const user = JSON.parse(userJson);
        if (!user.userID) {
          this.$message.error('用户ID不存在，请重新登录');
          this.$router.push('/login');
          return false;
        }
      } catch (error) {
        console.error('解析用户信息失败:', error);
        this.$message.error('用户信息格式错误，请重新登录');
        this.$router.push('/login');
        return false;
      }
      
      return true;
    },    // 获取聊天列表
    // 获取聊天列表
    fetchChats() {
      this.loading = true;
      // 使用request模块获取聊天记录
      request.get('/chats')        .then(res => {
          console.log('格式化的数据:', JSON.stringify(res, null, 2));
          // 假设API返回数据格式为数组，每个元素包含id, title, lastMessage等字段
          if (res && (res.code=="200" || res.code=="0") && Array.isArray(res.data)) {
            // 处理返回的数据，确保每个聊天记录都有正确的日期对象
            this.chats = res.data.map(chat => ({
              id: chat.chatId,  // 将后端的 chatId 映射为前端的 id
              title: chat.title || "新的会话",
              avatar: this.botAvatar, // 设置默认头像
              time: this.formatMessageTime(chat.updatedAt), // 格式化时间显示
              createdAt: new Date(chat.createdAt || Date.now()), // 确保createdAt是Date对象
              updatedAt: new Date(chat.updatedAt || Date.now()) // 确保updatedAt是Date对象
            }));
            // 按最近访问时间排序
            this.sortChatsByTime();
          }
        })
        .catch(error => {
          console.error('获取聊天记录失败:', error);
          this.$message.error('获取聊天记录失败，请稍后重试');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    sortChatsByTime() {
      this.chats.sort((a, b) => b.updatedAt - a.updatedAt);
    },
    createNewChat() {
      // 创建新的聊天会话
      request.post('/chats', {
        title: "新的会话"
      })
      .then(res => {
        console.log('创建新的聊天会话,格式化的数据:', JSON.stringify(res, null, 2));
        const chat = res.data; // 假设返回的数据是一个数组，取第一个元素
        const newChat = {
          id: chat.chatId,  // 将后端的 chatId 映射为前端的 id
          title: chat.title || "新的会话",
          avatar: this.botAvatar, // 设置默认头像
          time: this.formatMessageTime(chat.updatedAt), // 格式化时间显示
          createdAt: new Date(chat.createdAt || Date.now()), // 确保createdAt是Date对象
          updatedAt: new Date(chat.updatedAt || Date.now()) // 确保updatedAt是Date对象
        };
        
        this.chats.unshift(newChat);
        this.selectContact(newChat.id);
        
        this.$message.success('创建成功');
      })
      .catch(error => {
        console.error('创建新聊天失败:', error);
        this.$message.error('创建新聊天失败，请稍后重试');
      });
    },
    selectContact(id) {
      this.activeContact = id;
      
      // 找到当前选择的聊天
      const chatIndex = this.chats.findIndex(chat => chat.id === id);
      
      // 加载消息
      this.loadMessages(id);
      
      // 滚动到最新消息
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    sendMessage() {
      if (!this.newMessage.trim()) return;
      
      // 添加新消息到本地显示
      this.messages.push({
        text: this.newMessage,
        time: this.getCurrentTime(),
        own: true
      });
      
      const sentMessage = this.newMessage;
      
      // 更新最后一条消息并更新访问时间（因为有新输入）
      const chatIndex = this.chats.findIndex(chat => chat.id === this.activeContact);
      if (chatIndex >= 0) {
        this.chats[chatIndex].time = "刚刚";
        
        // 只在发送消息时更新访问时间
        this.chats[chatIndex].updatedAt = this.messages[this.messages.length - 1].time;
        
        // 如果这是新的聊天，并且是第一条消息，则以该消息作为标题
        if (this.chats[chatIndex].title === "新的会话" && this.messages.length === 1) {
          this.chats[chatIndex].title = sentMessage.length > 15 
            ? sentMessage.substring(0, 15) + "..." 
            : sentMessage;
            
          // 更新后端的聊天标题
          request.put(`/chats/${this.activeContact}`, {
            title: this.chats[chatIndex].title
          }).catch(error => {
            console.error('初始化聊天标题失败:', error);
          });
        }
        
        this.sortChatsByTime();
      }
      
      // 清空输入
      this.newMessage = "";
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
      
      // 显示正在输入提示
      this.showTypingIndicator();
      
      // 发送消息到后端并获取回复，单独设置超时时间为60秒
      request.post(
        `/chats/${this.activeContact}/messages`,
        { content: sentMessage },
        { timeout: 90000 } // 单独设置超时时间为60秒
      )
      .then(res => {
        console.log('格式化回答:', JSON.stringify(res, null, 2));        // 移除typing指示器
        this.messages = this.messages.filter(m => !m.isTyping);        // 处理data里的数据，假设res.data为回复内容
        if (res && (res.code=="200" || res.code=="0") && res.data) {          this.messages.push({
            chatId: res.data.chatId,
            messageId: res.data.messageId,
            own: res.data.isUser,  // 映射isUser到own以匹配前端模板
            text: res.data.text,   // 修正字段名拼写错误
            time: this.formatMessageTime(res.data.createdTime),  // 添加time字段以匹配前端模板
            ragInfo: res.data.ragInfo  // 添加RAG信息
          });
          
          // 调试RAG信息
          console.log('RAG信息:', res.data.ragInfo);
          if (res.data.ragInfo && res.data.ragInfo.basedOnRag) {
            console.log('检测到RAG增强回答，应该显示RAG信息');
          }
        } else {
          this.messages.push({
        text: '离线啦！',
        time: this.getCurrentTime(),
        own: false
          });
        }
        
        // 更新聊天列表中的最后一条消息
        const chatIndex = this.chats.findIndex(chat => chat.id === this.activeContact);
        if (chatIndex >= 0) {
          this.chats[chatIndex].time = "刚刚";
          this.sortChatsByTime();
        }
        
        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      })
      .catch(error => {
        console.error('发送消息失败:', error);
        this.$message.error('发送消息失败，请稍后重试');
        
        // 移除typing指示器
        this.messages = this.messages.filter(m => !m.isTyping);
      });
    },
    deleteChat(chatId) {
      this.$confirm('确认删除此聊天记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 使用request删除聊天
        request.delete(`/chats/${chatId}`)
          .then(() => {
            // 删除聊天
            const index = this.chats.findIndex(chat => chat.id === chatId);
            if (index !== -1) {
              this.chats.splice(index, 1);
              this.activeContact = null;
              this.messages = [];
            }
            
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          })
          .catch(error => {
            console.error('删除聊天记录错误:', error);
            this.$message.error('删除聊天记录失败，请稍后重试');
          });
      }).catch(() => {
        // 用户取消删除
      });
    },
    openRenameDialog(chatId) {
      const chat = this.chats.find(c => c.id === chatId);
      if (chat) {
        this.currentEditingChatId = chatId;
        this.newTitle = chat.title;
        console.log('打开重命名对话框', chatId, chat.title);
        this.dialogVisible = true;
        this.$nextTick(() => {
          // 这里要用 $refs.titleInput.$el.querySelector('input') 聚焦 input
          if (this.$refs.titleInput && this.$refs.titleInput.$el) {
            const input = this.$refs.titleInput.$el.querySelector('input');
            if (input) input.focus();
          }
        });
      }
    },
    confirmRename() {
      if (!this.newTitle.trim()) {
        this.$message.error('标题不能为空');
        return;
      }
      
      // 使用request修改聊天标题
      request.put(`/chats/${this.currentEditingChatId}`, {
        title: this.newTitle
      })
      .then(res => {
        const chatIndex = this.chats.findIndex(chat => chat.id === this.currentEditingChatId);
        if (chatIndex !== -1 && res && (res.code=="200" || res.code=="0")) {
          this.chats[chatIndex].title = this.newTitle;
          this.$message({
            type: 'success',
            message: '标题修改成功!'
          });
        }else {
          this.$message.error('标题修改失败，请稍后重试');
        }        
        this.dialogVisible = false;
        this.newTitle = "";
        this.currentEditingChatId = null;
      })
      .catch(error => {
        console.error('修改聊天标题错误:', error);
        this.$message.error('修改标题失败，请稍后重试');
      });
    },
    showTypingIndicator() {
      this.messages.push({
        text: "正在输入...",
        time: this.getCurrentTime(),
        own: false,
        isTyping: true
      });
    },    loadMessages(chatId) {
      // 使用request获取消息记录
      request.get(`/chats/${chatId}/messages`)
        .then(res => {
          console.log('获取消息记录响应:', JSON.stringify(res, null, 2));
          
          if (res && (res.code=="200" || res.code=="0")) {
            let messagesData = [];
            
            // 处理不同的响应格式
            if (Array.isArray(res.data)) {
              // 如果返回的是数组
              messagesData = res.data;
            } else if (res.data && typeof res.data === 'object') {
              // 如果返回的是单个对象，包装成数组
              messagesData = [res.data];
            }
              this.messages = messagesData.map(msg => {
              console.log('处理消息:', msg);
              return {
                chatId: msg.chatId,
                messageId: msg.messageId,
                own: msg.isUser,  // 映射isUser到own以匹配前端模板
                text: msg.text,   // 修正字段名拼写错误
                time: this.formatMessageTime(msg.createdTime),  // 添加time字段以匹配前端模板
                ragInfo: msg.ragInfo  // 添加RAG信息
              };
            });
          } else {
            // 处理响应格式不符合预期的情况
            this.messages = [];
            console.warn('消息记录格式不符合预期:', res);
          }        })
        .catch(error => {
          console.error('获取消息记录失败:', error);
          this.$message.error('获取消息记录失败，请稍后重试');
          this.messages = [];
        });
    },
    formatMessageTime(timestamp) {
      if (!timestamp) return this.getCurrentTime();
      
      const date = new Date(timestamp);
      const now = new Date();
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      
      // 如果是今天的消息，只显示时间
      if (date.toDateString() === now.toDateString()) {
        return `${hours}:${minutes}`;
      }
      
      // 如果是昨天的消息
      const yesterday = new Date(now);
      yesterday.setDate(now.getDate() - 1);
      if (date.toDateString() === yesterday.toDateString()) {
        return `昨天 ${hours}:${minutes}`;
      }
      
      // 其他情况显示日期
      return `${date.getMonth() + 1}-${date.getDate()} ${hours}:${minutes}`;
    },
    getActiveChatTitle() {
      const chat = this.chats.find(c => c.id === this.activeContact);
      return chat ? chat.title : '会话';
    },
    getActiveChatAvatar() {
      const chat = this.chats.find(c => c.id === this.activeContact);
      return chat ? chat.avatar : this.botAvatar;
    },
    scrollToBottom() {
      const container = this.$refs.messagesContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },    getCurrentTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
      // 格式化消息文本，处理think部分、括号提示文本、Markdown格式并为英文单词添加点击功能
    formatMessageText(text) {
      if (!text) return '';
      
      // 首先处理并移除think部分
      let processedText = this.removeThinkContent(text);
      
      // 渲染Markdown格式
      processedText = this.renderMarkdown(processedText);
      
      // 处理括号中的提示文本，如: *(Remember, you can tell me about your day!)*
      // 移除外层括号和星号，并用不同颜色显示
      processedText = processedText.replace(/\*?\(([^)]+)\)\*?/g, (match, content) => {
        return `<span class="hint-text">${content}</span>`;
      });
      
      // 英文单词的正则表达式 - 匹配连续的英文字母（至少2个字符）
      // 但不要匹配已经被span标签包围的内容
      const wordRegex = /\b[a-zA-Z]{2,}\b(?![^<]*>)/g;
      return processedText.replace(wordRegex, (match) => {
        // 排除一些常见的非实词（可根据需要扩展）
        const skipWords = ['the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might', 'can', 'this', 'that', 'these', 'those', 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'my', 'your', 'his', 'her', 'its', 'our', 'their'];
        
        if (skipWords.includes(match.toLowerCase())) {
          return match; // 保持原样，不添加点击功能
        }
        
        return `<span class="clickable-word" 
                      data-word="${match.toLowerCase()}" 
                      onclick="if(window.handleWordClick) window.handleWordClick('${match.toLowerCase()}')">${match}</span>`;
      });    
    },      // 自定义Markdown渲染方法
    renderMarkdown(text) {

      if (!text) return '';
      
      let html = text;
      
      // 预处理：去掉行首和行尾多余的空格，但保留有意义的缩进
      html = html.split('\n').map(line => {
        // 如果是代码块或者有特殊缩进意义的行，保持原样
        if (line.match(/^```|^\s*[-*+]\s|^\s*\d+\.\s|^\s*>/)) {
          return line;
        }
        return line.trim();
      }).join('\n');
      
      // 1. 处理代码块 (```code```) - 首先处理以避免后续处理影响
      html = html.replace(/```([\s\S]*?)```/g, (match, code) => {
        return `<pre class="markdown-code-block"><code>${this.escapeHtml(code.trim())}</code></pre>`;
      });
      
      // 2. 处理行内代码 (`code`) - 在处理其他格式之前
      html = html.replace(/`([^`\n]+)`/g, (match, code) => {
        return `<code class="markdown-inline-code">${this.escapeHtml(code)}</code>`;
      });
      
      // 3. 处理表格 - 在处理其他格式之前
      html = this.renderTable(html);
      
      // 4. 处理标题 (# ## ###) - 必须在行首
      html = html.replace(/^(#{1,6})\s+(.+)$/gm, (match, hashes, title) => {
        const level = hashes.length;
        return `<h${level} class="markdown-heading markdown-h${level}">${title.trim()}</h${level}>`;
      });
      
      // 5. 处理粗体 (**text** 或 __text__)
      html = html.replace(/\*\*([^*\n]+?)\*\*/g, '<strong class="markdown-bold">$1</strong>');
      html = html.replace(/__([^_\n]+?)__/g, '<strong class="markdown-bold">$1</strong>');
      
      // 6. 处理斜体 (*text* 或 _text_) - 避免与粗体冲突
      html = html.replace(/(?<!\*)\*([^*\n]+?)\*(?!\*)/g, '<em class="markdown-italic">$1</em>');
      html = html.replace(/(?<!_)_([^_\n]+?)_(?!_)/g, '<em class="markdown-italic">$1</em>');
      
      // 7. 处理删除线 (~~text~~)
      html = html.replace(/~~([^~\n]+?)~~/g, '<del class="markdown-strikethrough">$1</del>');
      
      // 8. 处理链接 [text](url) - 在处理其他格式之后
      html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, 
        '<a href="$2" class="markdown-link" target="_blank" rel="noopener noreferrer">$1</a>');
      
      // 9. 处理引用 (> text) - 必须在行首
      html = html.replace(/^>\s*(.+)$/gm, '<blockquote class="markdown-blockquote">$1</blockquote>');
      
      // 10. 处理无序列表 (- 或 * 或 +) - 必须在行首
      html = html.replace(/^[\s]*[-*+]\s+(.+)$/gm, '<li class="markdown-list-item">$1</li>');
      // 将连续的列表项包装在ul中
      html = html.replace(/(<li class="markdown-list-item">.*?<\/li>)(\s*<li class="markdown-list-item">.*?<\/li>)*/g, 
        '<ul class="markdown-list">$&</ul>');
      
      // 11. 处理有序列表 (1. 2. 3.) - 必须在行首
      html = html.replace(/^[\s]*\d+\.\s+(.+)$/gm, '<li class="markdown-ordered-list-item">$1</li>');
      // 将连续的有序列表项包装在ol中
      html = html.replace(/(<li class="markdown-ordered-list-item">.*?<\/li>)(\s*<li class="markdown-ordered-list-item">.*?<\/li>)*/g, 
        '<ol class="markdown-ordered-list">$&</ol>');
      
      // 12. 处理分隔线 (--- 或 ***) - 必须在单独一行
      html = html.replace(/^(---+|\*\*\*+)$/gm, '<hr class="markdown-hr">');
        // 13. 优化的段落和换行处理
      // 首先清理多余的连续换行
      html = html.replace(/\n{3,}/g, '\n\n');
      
      // 将双换行转换为段落分隔符
      html = html.replace(/\n\n/g, '__PARAGRAPH_BREAK__');
      
      // 对于单个换行，只在特定情况下转换为<br>
      html = html.replace(/\n/g, (match, offset, string) => {
        const beforeMatch = string.substring(0, offset);
        const afterMatch = string.substring(offset + 1);
        
        // 如果在HTML标签内，保持换行
        if (beforeMatch.match(/<(table|ul|ol|pre|blockquote)[^>]*>(?![\s\S]*<\/\1>)/) ||
            afterMatch.match(/^[\s]*<\/(table|ul|ol|pre|blockquote)>/)) {
          return '\n';
        }
        
        // 如果前一行或后一行是空的，不需要<br>
        const beforeLines = beforeMatch.split(/(?:\n|__PARAGRAPH_BREAK__)/);
        const afterLines = afterMatch.split(/(?:\n|__PARAGRAPH_BREAK__)/);
        const lastLine = beforeLines[beforeLines.length - 1] || '';
        const nextLine = afterLines[0] || '';
        
        // 如果前一行或后一行为空，或者包含HTML块级元素，则不添加<br>
        if (!lastLine.trim() || !nextLine.trim() || 
            lastLine.match(/<\/(h[1-6]|div|table|ul|ol|blockquote|pre|hr|p)>/) ||
            nextLine.match(/^<(h[1-6]|div|table|ul|ol|blockquote|pre|hr|p)/) ||
            lastLine.match(/^\s*[-*+\d]+\.?\s/) || // 列表项
            nextLine.match(/^\s*[-*+\d]+\.?\s/)) {  // 列表项
          return ' '; // 用空格替代，在段落处理时会被清理
        }
        
        return '<br>';
      });
      
      // 处理段落分割
      const paragraphs = html.split('__PARAGRAPH_BREAK__');
      const processedParagraphs = paragraphs.map(para => {
        let trimmed = para.trim();
        if (!trimmed) return '';
        
        // 清理段落内多余的空格
        trimmed = trimmed.replace(/\s+/g, ' ');
        
        // 如果已经是块级元素，不需要包装在<p>中
        if (trimmed.match(/^<(h[1-6]|div|table|ul|ol|blockquote|pre|hr)/)) {
          return trimmed;
        }
        
        return `<p class="markdown-paragraph">${trimmed}</p>`;
      }).filter(para => para);
      
      html = processedParagraphs.join('');
      
      // 如果没有任何块级元素，包装整个内容
      if (!html.match(/<(p|h[1-6]|div|table|ul|ol|blockquote|pre|hr)/)) {
        html = `<p class="markdown-paragraph">${html}</p>`;
      }
      
      // 最终清理：移除多余的空格和换行
      html = html.replace(/\s+<\/p>/g, '</p>');
      html = html.replace(/<p[^>]*>\s+/g, match => match.replace(/\s+$/, ''));
      html = html.replace(/<br>\s*<br>/g, '<br>');
      html = html.replace(/\s+<br>/g, '<br>');
      html = html.replace(/<br>\s+/g, '<br>');
      
      return html;},
    
    // 处理Markdown表格的方法
    renderTable(text) {
      // 匹配表格模式：至少两行，第二行是分隔符行
      const tableRegex = /(?:^|\n)((?:\|[^\n]+\|\n)+)\|(\s*:?-+:?\s*\|)+(\s*:?-+:?\s*)*\n((?:\|[^\n]+\|\n?)*)/gm;
      
      return text.replace(tableRegex, (match, headerRow, separatorRow, _, bodyRows) => {
        // 解析表头
        const headers = headerRow.trim().split('\n')[0]
          .split('|')
          .filter(cell => cell.trim())
          .map(cell => cell.trim());
        
        // 解析对齐方式
        const alignments = separatorRow.split('|')
          .filter(cell => cell.trim())
          .map(cell => {
            const trimmed = cell.trim();
            if (trimmed.startsWith(':') && trimmed.endsWith(':')) return 'center';
            if (trimmed.endsWith(':')) return 'right';
            return 'left';
          });
        
        // 解析数据行
        const rows = bodyRows.trim()
          .split('\n')
          .filter(row => row.trim())
          .map(row => 
            row.split('|')
              .filter(cell => cell.trim() || row.indexOf(cell) !== 0) // 保留空单元格，但不包括开头的空字符串
              .map(cell => cell.trim())
          );
        
        // 生成HTML表格
        let tableHtml = '<table class="markdown-table">';
        
        // 表头
        if (headers.length > 0) {
          tableHtml += '<thead class="markdown-table-head"><tr>';
          headers.forEach((header, index) => {
            const align = alignments[index] || 'left';
            tableHtml += `<th class="markdown-table-header" style="text-align: ${align}">${header}</th>`;
          });
          tableHtml += '</tr></thead>';
        }
        
        // 表体
        if (rows.length > 0) {
          tableHtml += '<tbody class="markdown-table-body">';
          rows.forEach(row => {
            if (row.length > 0) {
              tableHtml += '<tr>';
              row.forEach((cell, index) => {
                const align = alignments[index] || 'left';
                tableHtml += `<td class="markdown-table-cell" style="text-align: ${align}">${cell || ''}</td>`;
              });
              tableHtml += '</tr>';
            }
          });
          tableHtml += '</tbody>';
        }
        
        tableHtml += '</table>';
        return tableHtml;
      });
    },
    
    // HTML转义工具方法
    escapeHtml(text) {
      const div = document.createElement('div');
      div.textContent = text;
      return div.innerHTML;
    },
    
    // 移除think内容的方法
    removeThinkContent(text) {
      if (!text) return '';
      
      // 匹配并移除 <think>...</think> 标签及其内容
      const thinkRegex = /<think>[\s\S]*?<\/think>/gi;
      let cleanedText = text.replace(thinkRegex, '');
      
      // 匹配并移除 think> 开头的内容（处理不完整的think标签）
      const incompleteThinkRegex = /think>[\s\S]*?(?=\n\n|\n[A-Z]|$)/gi;
      cleanedText = cleanedText.replace(incompleteThinkRegex, '');
      
      // 清理多余的空白行
      cleanedText = cleanedText.replace(/\n\s*\n\s*\n/g, '\n\n');
      
      return cleanedText.trim();
    },
      // 处理单词点击事件
    handleWordClick(word) {
      if (!word) return;
      
      console.log('点击单词:', word); // 调试日志
        // 跳转到单词详情页面，并传递来源页面信息
      this.$router.push({
        path: `/word/${encodeURIComponent(word)}`,
        query: { from: '/chat' }
      }).catch(err => {
        console.error('路由跳转失败:', err);
        this.$message.error('跳转单词详情页面失败');
      });
    },
    
    // 根据相似度获取颜色
    getSimilarityColor(similarity) {
      if (similarity >= 0.8) return '#67C23A'; // 绿色 - 高相似度
      if (similarity >= 0.6) return '#E6A23C'; // 橙色 - 中等相似度
      return '#F56C6C'; // 红色 - 低相似度
    },
    
    // 根据相似度获取标签类型
    getSimilarityTagType(similarity) {
      if (similarity >= 0.8) return 'success'; // 高相似度
      if (similarity >= 0.6) return 'warning'; // 中等相似度
      return 'danger'; // 低相似度
    },
    
    // 计算回答可信度百分比
    getConfidencePercentage(ragInfo) {
      if (!ragInfo) return 0;
      
      // 综合考虑相似度、有效结果数量等因素
      const similarityScore = ragInfo.maxSimilarity * 60; // 最高相似度占60%权重
      const validityScore = Math.min(ragInfo.validRagCount / ragInfo.ragCount, 1) * 25; // 有效比例占25%权重
      const coverageScore = Math.min(ragInfo.ragCount / 5, 1) * 15; // 检索覆盖度占15%权重
      
      return Math.round(similarityScore + validityScore + coverageScore);
    },
    
    // 获取可信度颜色
    getConfidenceColor(ragInfo) {
      const percentage = this.getConfidencePercentage(ragInfo);
      if (percentage >= 80) return '#67C23A'; // 绿色 - 高可信度
      if (percentage >= 60) return '#E6A23C'; // 橙色 - 中等可信度
      return '#F56C6C'; // 红色 - 低可信度
    },
    
    // 获取可信度文本
    getConfidenceText(ragInfo) {
      const percentage = this.getConfidencePercentage(ragInfo);
      if (percentage >= 80) return '高';
      if (percentage >= 60) return '中';
      return '低';
    }
  },
  mounted() {
    // 在组件挂载后设置全局的单词点击处理函数
    window.handleWordClick = (word) => {
      this.handleWordClick(word);
    };
    
    // 添加事件委托处理点击事件
    this.handleContainerClick = (event) => {
      const target = event.target;
      if (target && target.classList.contains('clickable-word')) {
        const word = target.getAttribute('data-word');
        if (word) {
          event.preventDefault();
          event.stopPropagation();
          this.handleWordClick(word);
        }
      }
    };
    
    this.$nextTick(() => {
      const messagesContainer = this.$refs.messagesContainer;
      if (messagesContainer) {
        messagesContainer.addEventListener('click', this.handleContainerClick);
      }
    });
  },
  beforeUnmount() {
    // 组件销毁前清理全局函数
    delete window.handleWordClick;
    
    // 清理事件监听器
    const messagesContainer = this.$refs.messagesContainer;
    if (messagesContainer) {
      messagesContainer.removeEventListener('click', this.handleContainerClick);
    }
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: rgb(239, 242, 245);
}

.chat-main {
  display: flex;
  flex: 1;
  overflow: hidden;
  margin: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: white;
}

.chat-sidebar {
  width: 300px;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.sidebar-header h3 {
  margin: 0 0 10px;
}

.new-chat-btn {
  margin-bottom: 10px;
  width: 100%;
}

.chat-contacts {
  flex: 1;
  overflow-y: auto;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #f5f5f5;
  position: relative;
}

.contact-item:hover {
  background-color: #f9f9f9;
}

.contact-item.active {
  background-color: #e6f7ff;
}

.contact-main {
  display: flex;
  flex: 1;
  align-items: center;
  cursor: pointer;
}

.contact-info {
  flex: 1;
  margin-left: 10px;
  overflow: hidden;
}

.contact-name {
  font-weight: bold;
  margin-bottom: 3px;
}

.contact-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-left: 10px;
}

.contact-actions {
  display: flex;
  align-items: center;
  opacity: 0.7; /* 默认稍微可见一些 */
  transition: opacity 0.3s;
  margin-left: 8px;
}

.contact-item:hover .contact-actions {
  opacity: 1;
}

.action-icon {
  margin-left: 8px;
  font-size: 18px;
  cursor: pointer;
  padding: 6px;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.edit-icon {
  color: #107edecd;
  background-color: rgba(64, 158, 255, 0.1);
}

.delete-icon {
  color: #F56C6C;
  background-color: rgba(245, 108, 108, 0.1);
}

.edit-icon:hover {
  background-color: rgba(64, 158, 255, 0.2);
  transform: scale(1.1);
}

.delete-icon:hover {
  background-color: rgba(245, 108, 108, 0.2);
  transform: scale(1.1);
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.chat-header h3 {
  margin: 0;
}

.messages-container {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.messages {
  display: flex;
  flex-direction: column;
}

.message {
  display: flex;
  margin-bottom: 15px;
  max-width: 80%;
}

.own-message {
  flex-direction: row-reverse;
  align-self: flex-end;
}

.message-content {
  margin: 0 10px;
}

.message-text {
  padding: 10px;
  border-radius: 10px;
  background-color: #e6f7ff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  white-space: pre-line;
}

.own-message .message-text {
  background-color: #95de64;
  color: white;
}

.message-time {
  font-size: 0.7em;
  color: #888;
  margin-top: 5px;
  text-align: right;
}

.no-chat-selected {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #aaa;
}

.chat-icon {
  width: 80px;
  height: 80px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.new-chat-big-btn {
  margin-top: 20px;
  padding: 12px 24px;
  font-size: 16px;
}

.chat-input {
  padding: 15px;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
}

.input-actions {
  margin-right: 10px;
}

.input-actions i {
  margin-right: 15px;
  font-size: 20px;
  color: #888;
  cursor: pointer;
}

.input-actions i:hover {
  color: #409EFF;
}

.input-field {
  flex: 1;
  margin-right: 10px;
  position: relative;
}

.input-field textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  height: 60px;
  outline: none;
}

.input-tip {
  position: absolute;
  right: 10px;
  bottom: -18px;
  color: #aaa;
  font-size: 12px;
}

/* 添加对话框样式 */
.rename-dialog {
  z-index: 3000 !important; /* 确保在最上层 */
  
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px;
}
/* .rename-dialog .el-dialog__body {
  padding: 20px;
  text-align: right;
} */ /* 非scoped样式部分 */
.rename-dialog .el-dialog {
  margin-top: 0 !important; /* 覆盖默认边距 */
  margin-bottom: 0 !important;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

/* RAG信息样式 */
.rag-info-container {
  background-color: #f0f8ff;
  border: 1px solid #d4edda;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.rag-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #155724;
}

.rag-header i {
  margin-right: 6px;
  color: #28a745;
}

.rag-stats {
  display: flex;
  gap: 6px;
}

.rag-results {
  margin-top: 8px;
}

.rag-result-item {
  background-color: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 10px;
  margin-bottom: 8px;
}

.rag-result-item:last-child {
  margin-bottom: 0;
}

.rag-result-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.similarity-score {
  font-size: 12px;
  font-weight: 600;
  color: #6b7280;
}

.rag-result-content {
  font-size: 13px;
  line-height: 1.4;
}

.rag-question {
  margin-bottom: 6px;
  color: #374151;
}

.rag-answer {
  color: #6b7280;
}

.rag-question strong,
.rag-answer strong {
  color: #1f2937;
  font-weight: 600;
}

/* 用户消息中的RAG信息样式调整 */
.own-message .rag-info-container {
  background-color: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.2);
}

.own-message .rag-header {
  color: rgba(255, 255, 255, 0.9);
}

.own-message .rag-header i {
  color: rgba(255, 255, 255, 0.8);
}

.own-message .rag-result-item {
  background-color: rgba(255, 255, 255, 0.05);
  border-color: rgba(255, 255, 255, 0.1);
}

.own-message .similarity-score {
  color: rgba(255, 255, 255, 0.7);
}

.own-message .rag-question,
.own-message .rag-answer {
  color: rgba(255, 255, 255, 0.8);
}

.own-message .rag-question strong,
.own-message .rag-answer strong {
  color: rgba(255, 255, 255, 0.95);
}

/* 确保消息容器的相对定位 */
.messages-container {
  position: relative !important;
}

/* 提示文本样式 - 使用更柔和的颜色 */
.message-text .hint-text {
  color: #9ca3af !important;
  font-style: italic !important;
  font-weight: normal !important;
  font-size: 0.85em !important;
  opacity: 0.8 !important;
  background-color: rgba(156, 163, 175, 0.08) !important;
  padding: 2px 6px !important;
  border-radius: 6px !important;
  margin: 0 2px !important;
  border-left: 2px solid rgba(156, 163, 175, 0.3) !important;
}

/* 用户消息中的提示文本样式 - 使用半透明白色 */
.own-message .message-text .hint-text {
  color: rgba(255, 255, 255, 0.75) !important;
  background-color: rgba(255, 255, 255, 0.1) !important;
  border-left: 2px solid rgba(255, 255, 255, 0.3) !important;
}

/* 可点击单词样式 - 与普通文字完全一致 */
.message-text .clickable-word {
  cursor: pointer !important;
  color: inherit !important;
  text-decoration: none !important;
  display: inline !important;
  font-weight: inherit !important;
  font-size: inherit !important;
  line-height: inherit !important;
  font-family: inherit !important;
  background: transparent !important;
  margin: 0 !important;
  padding: 0 !important;
  border-radius: 0 !important;
  transition: none !important;
  border-bottom: none !important;
}

/* 可点击单词悬停效果 - 保持最小变化 */
.message-text .clickable-word:hover {
  background-color: transparent !important;
  color: inherit !important;
  border-bottom: none !important;
  transform: none !important;
}

/* 用户消息中的可点击单词样式 - 与普通文字一致 */
.own-message .message-text .clickable-word {
  color: inherit !important;
  font-weight: inherit !important;
  font-family: inherit !important;
}

/* 用户消息中的可点击单词悬停效果 - 保持一致 */
.own-message .message-text .clickable-word:hover {
  background-color: transparent !important;
  color: inherit !important;
  border-bottom: none !important;
}

/* Markdown样式 */
.message-text .markdown-heading {
  margin: 8px 0 4px 0 !important;
  font-weight: bold !important;
  line-height: 1.3 !important;
}

.message-text .markdown-h1 {
  font-size: 1.5em !important;
  border-bottom: 2px solid #e1e4e8 !important;
  padding-bottom: 4px !important;
}

.message-text .markdown-h2 {
  font-size: 1.3em !important;
  border-bottom: 1px solid #e1e4e8 !important;
  padding-bottom: 3px !important;
}

.message-text .markdown-h3 {
  font-size: 1.2em !important;
}

.message-text .markdown-h4,
.message-text .markdown-h5,
.message-text .markdown-h6 {
  font-size: 1.1em !important;
}

.message-text .markdown-code-block {
  background-color: #f6f8fa !important;
  border: 1px solid #e1e4e8 !important;
  border-radius: 6px !important;
  padding: 12px !important;
  margin: 8px 0 !important;
  overflow-x: auto !important;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace !important;
  font-size: 0.85em !important;
  line-height: 1.4 !important;
}

.message-text .markdown-inline-code {
  background-color: rgba(175, 184, 193, 0.2) !important;
  border-radius: 3px !important;
  padding: 2px 4px !important;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace !important;
  font-size: 0.9em !important;
}

.message-text .markdown-bold {
  font-weight: bold !important;
}

.message-text .markdown-italic {
  font-style: italic !important;
}

.message-text .markdown-strikethrough {
  text-decoration: line-through !important;
}

.message-text .markdown-list,
.message-text .markdown-ordered-list {
  margin: 8px 0 !important;
  padding-left: 20px !important;
}

.message-text .markdown-list-item,
.message-text .markdown-ordered-list-item {
  margin: 2px 0 !important;
  line-height: 1.4 !important;
}

.message-text .markdown-blockquote {
  border-left: 4px solid #dfe2e5 !important;
  padding: 8px 12px !important;
  margin: 8px 0 !important;
  background-color: rgba(175, 184, 193, 0.1) !important;
  font-style: italic !important;
  color: #6a737d !important;
}

.message-text .markdown-link {
  color: #0366d6 !important;
  text-decoration: none !important;
  border-bottom: 1px solid transparent !important;
  transition: border-bottom-color 0.2s !important;
}

.message-text .markdown-link:hover {
  border-bottom-color: #0366d6 !important;
}

.message-text .markdown-hr {
  border: none !important;
  border-top: 2px solid #e1e4e8 !important;
  margin: 16px 0 !important;
}

.message-text .markdown-paragraph {
  margin: 4px 0 !important;
  line-height: 1.5 !important;
}

.message-text .markdown-table {
  border-collapse: collapse !important;
  width: 100% !important;
  margin: 12px 0 !important;
  border: 1px solid #e1e4e8 !important;
  border-radius: 6px !important;
  overflow: hidden !important;
}

.message-text .markdown-table-head {
  background-color: #f6f8fa !important;
}

.message-text .markdown-table-header {
  padding: 8px 12px !important;
  border-bottom: 1px solid #e1e4e8 !important;
  border-right: 1px solid #e1e4e8 !important;
  font-weight: 600 !important;
  text-align: left !important;
  font-size: 0.9em !important;
}

.message-text .markdown-table-header:last-child {
  border-right: none !important;
}

.message-text .markdown-table-body tr:nth-child(even) {
  background-color: #f6f8fa !important;
}

.message-text .markdown-table-body tr:hover {
  background-color: #f1f3f4 !important;
}

.message-text .markdown-table-cell {
  padding: 8px 12px !important;
  border-bottom: 1px solid #e1e4e8 !important;
  border-right: 1px solid #e1e4e8 !important;
  text-align: left !important;
  font-size: 0.9em !important;
  line-height: 1.4 !important;
}

.message-text .markdown-table-cell:last-child {
  border-right: none !important;
}

.message-text .markdown-table-body tr:last-child .markdown-table-cell {
  border-bottom: none !important;
}

/* 用户消息中的Markdown样式调整 */
.own-message .message-text .markdown-code-block {
  background-color: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  color: rgba(255, 255, 255, 0.95) !important;
}

.own-message .message-text .markdown-inline-code {
  background-color: rgba(255, 255, 255, 0.15) !important;
  color: rgba(255, 255, 255, 0.95) !important;
}

.own-message .message-text .markdown-blockquote {
  border-left-color: rgba(255, 255, 255, 0.3) !important;
  background-color: rgba(255, 255, 255, 0.1) !important;
  color: rgba(255, 255, 255, 0.8) !important;
}

.own-message .message-text .markdown-link {
  color: rgba(255, 255, 255, 0.9) !important;
}

.own-message .message-text .markdown-link:hover {
  border-bottom-color: rgba(255, 255, 255, 0.9) !important;
}

.own-message .message-text .markdown-hr {
  border-top-color: rgba(255, 255, 255, 0.3) !important;
}

.own-message .message-text .markdown-h1,
.own-message .message-text .markdown-h2 {
  border-bottom-color: rgba(255, 255, 255, 0.3) !important;
}

.own-message .message-text .markdown-table {
  border-color: rgba(255, 255, 255, 0.2) !important;
}

.own-message .message-text .markdown-table-head {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

.own-message .message-text .markdown-table-header {
  border-bottom-color: rgba(255, 255, 255, 0.2) !important;
  border-right-color: rgba(255, 255, 255, 0.2) !important;
  color: rgba(255, 255, 255, 0.95) !important;
}

.own-message .message-text .markdown-table-body tr:nth-child(even) {
  background-color: rgba(255, 255, 255, 0.05) !important;
}

.own-message .message-text .markdown-table-body tr:hover {
  background-color: rgba(255, 255, 255, 0.08) !important;
}

.own-message .message-text .markdown-table-cell {
  border-bottom-color: rgba(255, 255, 255, 0.2) !important;
  border-right-color: rgba(255, 255, 255, 0.2) !important;
  color: rgba(255, 255, 255, 0.9) !important;
}

/* RAG信息样式 */
.rag-info-container {
  background-color: #f0f8ff;
  border: 1px solid #d4edda;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.rag-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #155724;
}

.rag-header i {
  margin-right: 6px;
  color: #28a745;
}

.rag-stats {
  display: flex;
  gap: 6px;
}

.rag-results {
  margin-top: 8px;
}

.rag-result-item {
  background-color: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 10px;
  margin-bottom: 8px;
}

.rag-result-item:last-child {
  margin-bottom: 0;
}

.rag-result-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.similarity-score {
  font-size: 12px;
  font-weight: 600;
  color: #6b7280;
}

.rag-result-content {
  font-size: 13px;
  line-height: 1.4;
}

.rag-question {
  margin-bottom: 6px;
  color: #374151;
}

.rag-answer {
  color: #6b7280;
}

.rag-question strong,
.rag-answer strong {
  color: #1f2937;
  font-weight: 600;
}

/* 用户消息中的RAG信息样式调整 */
.own-message .rag-info-container {
  background-color: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.2);
}

.own-message .rag-header {
  color: rgba(255, 255, 255, 0.9);
}

.own-message .rag-header i {
  color: rgba(255, 255, 255, 0.8);
}

.own-message .rag-result-item {
  background-color: rgba(255, 255, 255, 0.05);
  border-color: rgba(255, 255, 255, 0.1);
}

.own-message .similarity-score {
  color: rgba(255, 255, 255, 0.7);
}

.own-message .rag-question,
.own-message .rag-answer {
  color: rgba(255, 255, 255, 0.8);
}

.own-message .rag-question strong,
.own-message .rag-answer strong {
  color: rgba(255, 255, 255, 0.95);
}
</style>

